<?php

namespace App\Traits;

use App\Facades\Sigma;

trait AutoCreateOrderNo
{
    /**
     * Notes   : 统一处理订单编号，所有带有单号的模型，都要有no字段
     *           格式为 ymdHis+5位微妙+1位校验码，一共是18位
     *
     * @Date   : 2023/3/30 10:30
     * @Author : <Jason.C>
     */
    protected static function bootAutoCreateOrderNo(): void
    {
        self::creating(function ($model) {
            $time = explode(' ', microtime());
            $no = date('ymdHis').sprintf('%05d', $time[0] * 1e5);
            $prefix = property_exists($model, 'orderNoPrefix') ? $model->orderNoPrefix : '';

            if (property_exists($model, 'orderNoField')) {
                $model->{$model->orderNoField} = $prefix.Sigma::orderNo($no);
            } else {
                $model->no = $prefix.Sigma::orderNo($no);
            }
        });
    }
}
